﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FileStorage.Caching.CacheContainers.ExpireByTime
{
    /// <summary>
    /// Removes _all_ items from the cache each time the period 'timespan'
    /// is passed since the previous time this happened.
    /// </summary>
    public class ExpireByTimeCacheContainer : BaseCacheContainer
    {
        private DateTime _momentWhenLastExpirationTookPlaceUTC;
        private TimeSpan _timeSpanBefore;

        public ExpireByTimeCacheContainer(TimeSpan timeSpanBefore)
        {
            _timeSpanBefore = timeSpanBefore;
            _momentWhenLastExpirationTookPlaceUTC = DateTime.UtcNow;
        }

        public override bool RequiresCleaning(string key)
        {
            bool result;

            if (_momentWhenLastExpirationTookPlaceUTC.Add(_timeSpanBefore) < DateTime.UtcNow)
            {
                //
                // time to clean up
                //
                result = true;
                //
                // reset expiration
                //
                _momentWhenLastExpirationTookPlaceUTC = DateTime.UtcNow;
            } 
            else
            {
                //
                //
                //
                result = false;
            }

            return result;
        }
    }
}
